import 'package:awak/common/db/db_helper.dart';
import 'package:awak/common/models/today_goal.dart';

class TodayGoalRepository {
  static final TodayGoalRepository _instance = TodayGoalRepository._internal();
  factory TodayGoalRepository() => _instance;
  TodayGoalRepository._internal();

  // 创建今日目标
  Future<int> createTodayGoal(TodayGoal todayGoal) async {
    final db = await DBHelper.database;
    return await db.insert('today_goal', todayGoal.toMap());
  }

  // 获取所有今日目标
  Future<List<TodayGoal>> getAllTodayGoals() async {
    final db = await DBHelper.database;
    final res = await db.query('today_goal', orderBy: 'id ASC');
    return res.map((map) => TodayGoal.fromMap(map)).toList();
  }

  // 根据用户ID获取今日目标
  Future<List<TodayGoal>> getTodayGoalsByUserId(int userId) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'today_goal',
      where: 'userId = ?',
      whereArgs: [userId],
      orderBy: 'id ASC',
    );
    return res.map((map) => TodayGoal.fromMap(map)).toList();
  }

  // 根据ID获取今日目标
  Future<TodayGoal?> getTodayGoalById(int id) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'today_goal',
      where: 'id = ?',
      whereArgs: [id],
      limit: 1,
    );
    if (res.isNotEmpty) {
      return TodayGoal.fromMap(res.first);
    }
    return null;
  }

  // 更新今日目标
  Future<int> updateTodayGoal(TodayGoal todayGoal) async {
    final db = await DBHelper.database;
    return await db.update(
      'today_goal',
      todayGoal.toMap(),
      where: 'id = ?',
      whereArgs: [todayGoal.id],
    );
  }

  // 删除今日目标
  Future<int> deleteTodayGoal(int id) async {
    final db = await DBHelper.database;
    return await db.delete(
      'today_goal',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  // 根据用户ID删除所有今日目标
  Future<int> deleteTodayGoalsByUserId(int userId) async {
    final db = await DBHelper.database;
    return await db.delete(
      'today_goal',
      where: 'userId = ?',
      whereArgs: [userId],
    );
  }

  // 批量删除今日目标
  Future<void> deleteTodayGoalsByIds(List<int> ids) async {
    final db = await DBHelper.database;
    final batch = db.batch();
    for (int id in ids) {
      batch.delete(
        'today_goal',
        where: 'id = ?',
        whereArgs: [id],
      );
    }
    await batch.commit();
  }
}
